package com.micro.frog.rbac.controller;

import com.micro.frog.common.base.PageRes;
import com.micro.frog.common.base.Result;
import com.micro.frog.rbac.dto.MenuDTO;
import com.micro.frog.rbac.dto.UserDetail;
import com.micro.frog.rbac.entity.MenuDO;
import com.micro.frog.rbac.service.MenuService;
import com.micro.frog.rbac.util.SubjectUtil;
import com.micro.frog.rbac.vo.MenuVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 菜单加载类
 *
 * @author :  ljh
 * @date : 2018/4/2
 **/
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping(value = "/rbac/menu")
public class MenuController {

    private final MenuService menuService;

    @GetMapping(value = "user")
    public Result<List<MenuVO>> userMenu(HttpServletRequest request) {
        UserDetail userDetail = SubjectUtil.getUser(request);
        if (userDetail == null) {
            return Result.error("用户未登录");
        }
        return Result.success(userDetail.getMenus());
    }

    @GetMapping(value = "/list")
    public Result<List<MenuVO>> list() {
        return Result.success(menuService.queryList(null));
    }

    @GetMapping(value = "/page")
    public Result<PageRes<MenuDO>> list(MenuDTO req) {
        return menuService.queryPage(req);
    }

    @PostMapping("/add")
    public Result addMenu(MenuVO req) {
        boolean flag = menuService.add(req);
        return flag ? Result.success("添加成功") : Result.error("添加失败");
    }

    @PostMapping("/delete")
    public Result deleteMenu(Long menuId) {
        boolean flag = menuService.delete(menuId);
        return flag ? Result.success("删除成功") : Result.error("删除失败");
    }

    @PostMapping("/update")
    public Result updateMenu(MenuVO req) {
        boolean flag = menuService.update(req);
        return flag ? Result.success("修改成功") : Result.error("修改失败");
    }

    @GetMapping("/tree")
    public Result tree() {
        return Result.success(menuService.tree());
    }
}
